/**
 *
 */
package com.aiou.security.authentication.wechat;

import com.aiou.security.properties.SecurityProperties;
import com.aiou.security.properties.WeChatProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author zyb
 */
@Component
public class WeChatCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private SecurityProperties securityProperties;

    @Autowired(required = false)
    private WeChatUserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        WeChatAuthenticationFilter weChatAuthenticationFilter = new WeChatAuthenticationFilter();
        weChatAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        weChatAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        weChatAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);

        WeChatProperties wechat = securityProperties.getWechat();
        WeChatCodeAuthenticationProvider smsCodeAuthenticationProvider = new WeChatCodeAuthenticationProvider(userDetailsService, wechat.getAppId(), wechat.getAppSecret());

        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(weChatAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }

}
